﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;

using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.NetworkInformation;

using System.Threading;
using System.IO;
using System.Net.Sockets;
using System.Management;
using System.Data.SqlClient;
using System.Runtime.InteropServices;
using System.Collections;
using SELF.Model;

namespace SELF
{
    public partial class frm_Main_New : Form
    {
        public frm_Main_New(string Branch)
        {
            InitializeComponent();
            this.WindowState = FormWindowState.Maximized;
            this.Disposed += new EventHandler(frm_Main_New_Disposed);
            this.FormClosed += new FormClosedEventHandler(frm_Main_New_FormClosed);
            //Config.Configurations.BranchID = Branch;
        }

        void frm_Main_New_FormClosed(object sender, FormClosedEventArgs e)
        {
            //set machine state
            SELF.Model.Leaning.SetMechineState(Leaning.StateMechine.Close);
            //throw new NotImplementedException();
        }

        void frm_Main_New_Disposed(object sender, EventArgs e)
        {
            trlisten.Abort();
        }
        lcmpt.Connection conn = new lcmpt.Connection();

        bool Check = true;
        LogService.Service LS = new SELF.LogService.Service();
        string ticketID;

        Thread trlisten;
        Thread trMapping;
        WaitDialog.CircleThick thickCircle;

        [DllImport("user32.dll", EntryPoint = "HideCaret")]
        public static extern long HideCaret(IntPtr hwnd);


        private bool FirstLoaded()
        {

            return true;
        }

        Thread thProgress;
        WaitDialog.ProgressbarMarquee proMar;
        private void showProgress()
        {
            thickCircle = new WaitDialog.CircleThick();
            thickCircle.ShowDialog(this);
            //proMar = new WaitDialog.ProgressbarMarquee();
            //proMar.ShowDialog();
        }

        private void frm_Main_New_Load(object sender, EventArgs e)
        {
            lcmpt.QueryLog._FileName = Application.StartupPath + "\\query.txt";

            timer1.Start();
            txtMain.SelectionStart = 0;
            txtMain.SelectionLength = 0;
            txtMain.SelectionAlignment = HorizontalAlignment.Right;
            SELF.Model.Leaning.SetMechineState(SELF.Model.Leaning.StateMechine.Open);
            string strHostName = Dns.GetHostName();
            IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
            IPAddress[] addr = ipEntry.AddressList;
            ipAddress = addr[0];

            trlisten = new Thread(ListenToServer);
            trlisten.Start();

            trMapping = new Thread(BatchMapDrive);
            trMapping.Start();

            thickCircle = new WaitDialog.CircleThick();
            thickCircle.ShowDialog(this);
            
            txtMain.Text = "";
        }

        public static bool IsDriveMapped(string sDriveLetter)
        {
            sDriveLetter = sDriveLetter.ToUpper();
            string[] DriveList = Environment.GetLogicalDrives();
            for (int i = 0; i < DriveList.Length; i++)
            {
                if (sDriveLetter + ":\\" == DriveList[i].ToString())
                {
                    return true;
                }
            }
            return false;
        }

        private void BatchUnmapDrive()
        {
            string sectionName = "ShareLink";
            string conf = Application.StartupPath + "\\Configurations.xml";

            DataTable dtLink = new DataTable();
            dtLink = lcmpt.StandardDoc.ConvertToDataTable(conf, sectionName);

            for (int i = 0; i < dtLink.Rows.Count; i++)
            {
                try
                {
                    string link = dtLink.Rows[i]["ShareLink"].ToString();
                    string point = dtLink.Rows[i]["MapPoint"].ToString();
                    string tmp = point.Replace(":","");

                    if (IsDriveMapped(tmp))
                    {
                        aejw.Network.NetworkDrive oNetDrive = new aejw.Network.NetworkDrive();
                        //Map drive with specified user credentials
                        oNetDrive.LocalDrive = point;
                        oNetDrive.ShareName = link;
                        oNetDrive.Force = true;
                        oNetDrive.UnMapDrive();
                    }
                }
                catch (Exception ex)
                {
                    //do something
                }
            }
        }

        private void BatchMapDrive()
        {
            string sectionName = "ShareLink";
            string conf = Application.StartupPath + "\\Configurations.xml";

            DataTable dtLink = new DataTable();
            dtLink = lcmpt.StandardDoc.ConvertToDataTable(conf, sectionName);

            for (int i = 0; i < dtLink.Rows.Count; i++)
            {
                try
                {
                    string link = dtLink.Rows[i]["ShareLink"].ToString();
                    string user = dtLink.Rows[i]["UserName"].ToString();
                    string pass = dtLink.Rows[i]["Password"].ToString();
                    string point = dtLink.Rows[i]["MapPoint"].ToString();
                    string tmp = point.Replace(":", "");
                    if (!IsDriveMapped(tmp))
                    {
                        aejw.Network.NetworkDrive oNetDrive = new aejw.Network.NetworkDrive();
                        //oNetDrive.Force = true;
                        oNetDrive.LocalDrive = point;
                        oNetDrive.ShareName = link;
                        oNetDrive.MapDrive(user, pass);
                    }
                    if (IsDriveMapped(tmp))
                    {
                        Config.Configurations.BranchID = dtLink.Rows[i]["Branch"].ToString();
                    }
                }
                catch (Exception Ex)
                { 
                    Console.WriteLine(Ex.Message); 
                }
                
            }
            //if include in thread
            this.Invoke((MethodInvoker)(delegate()
            {
                //Thread.Sleep(2000);
                thickCircle.Close();
                trMapping.Abort();
            }));
        }

        int TTime = 0;
        ArrayList Arr = new ArrayList();
        private void timer1_Tick(object sender, EventArgs e)
        {
            ChangeTicker(txtMain);
            HideCaret(txtMain.Handle);
        }

        private void timer2_Tick(object sender, EventArgs e)
        {

        }
            
        public void LoadPage()
        {
            Image image_bg = Image.FromFile(cGobal.ImagePath.ToString() + cGobal.ThemeID.ToString() + @"\PicMain\jigsawMain1.png");
            tableLayoutPanel1.BackgroundImage = image_bg;
            //Image image_bg1 = Image.FromFile(cGobal.ImagePath.ToString() + cGobal.ThemeID.ToString() + @"\PicMain\jigsawMain_C.png");
            //tableLayoutPanel2.BackgroundImage = image_bg1;
        }

        #region Theme change
        private void button14_Click(object sender, EventArgs e)
        {
            cGobal.ThemeID = "Theme01_Red";
            LoadPage();
        }

        private void button15_Click(object sender, EventArgs e)
        {
            cGobal.ThemeID = "Theme02_Yellow";
            LoadPage();
        }

        private void button16_Click(object sender, EventArgs e)
        {
            cGobal.ThemeID = "Theme03_Pink";
            LoadPage();
        }

        private void button17_Click(object sender, EventArgs e)
        {
            cGobal.ThemeID = "Theme04_Green";
            LoadPage();
        }

        private void button18_Click(object sender, EventArgs e)
        {
            cGobal.ThemeID = "Theme05_Orange";
            LoadPage();
        }

        private void button19_Click(object sender, EventArgs e)
        {
            //cGobal.ThemeID = "Theme06_Blue";
            //LoadPage();
        }

        private void button20_Click(object sender, EventArgs e)
        {
            cGobal.ThemeID = "Theme07_Violet";
            LoadPage();
        }
        #endregion

        private string MacAddress()
        {

            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            string MacAddress = "";
            for (int x = 0; x < nics.Length; x++)
            {
                if (nics[x].NetworkInterfaceType == NetworkInterfaceType.Ethernet || nics[x].NetworkInterfaceType == NetworkInterfaceType.Ethernet3Megabit)
                {

                    MacAddress = "" + nics[x].GetPhysicalAddress();
                }
            }

            return MacAddress; 

        }

        private void timer3_Tick(object sender, EventArgs e)
        {
            //string IP = GetIP();
            //string ErrorMsg = "";
            //if (!LS.setAppLog(IP, "1", "Open", out ErrorMsg))
            //{
            //    MessageBox.Show(ErrorMsg);
            //}

        }

        private void button21_Click(object sender, EventArgs e)
        {
            SELF.Model.Leaning.SetMechineState(Leaning.StateMechine.Close);
            Application.Exit();
        }

        private void txtMain_TextChanged_1(object sender, EventArgs e)
        {

        }

        private void txtMain_KeyPress_1(object sender, KeyPressEventArgs e)
        {
            int cInt = Convert.ToInt32(e.KeyChar);
            if ((int)e.KeyChar >= 48 && (int)e.KeyChar <= 57 || cInt == 8)
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }

            //txtMain.UseSystemPasswordChar = false;
            //timer1.Enabled = false;
            //timer2.Enabled = true;
        }

        public enum ShutDown
        {
            LogOff = 0,
            Shutdown = 1,
            Reboot = 2,
            ForcedLogOff = 4,
            ForcedShutdown = 5,
            ForcedReboot = 6,
            PowerOff = 8,
            ForcedPowerOff = 12
        }

        IPAddress ipAddress;
        
        #region connect with remote admin

        private void ListenToServer()
        {
            bool LISTENING = false;
            IPAddress localhostAddress = ipAddress;
            int port = 63000;
            //' PORT ADDRESS
            ///'''''''' making socket tcpList ''''''''''''''''
            TcpListener tcpList = new TcpListener(localhostAddress, port);
            try
            {
                tcpList.Start();
                LISTENING = true;

                while (LISTENING)
                {
                    while (tcpList.Pending() == false & LISTENING == true)
                    {
                        // Yield the CPU for a while.
                        Thread.Sleep(10);
                    }
                    if (!LISTENING)
                        break; // TODO: might not be correct. Was : Exit Do

                    TcpClient tcpCli = tcpList.AcceptTcpClient();
                    //ListBox1.Items.Add("Data from " & "128.10.20.63")
                    NetworkStream ns = tcpCli.GetStream();
                    StreamReader sr = new StreamReader(ns);
                    ///'''''' get data from client '''''''''''''''
                    string receivedData = sr.ReadLine();

                    if (receivedData != "###SHUTDOWN###" && receivedData != "###REBOOT###" && receivedData != "###LOGOFF###")
                    {
                        {
                            //MessageBox.Show(receivedData);
                            this.Invoke((MethodInvoker)delegate
                            {
                                using (MessageBoxCustom messageBoxCustom = new MessageBoxCustom(receivedData, 10))
                                {
                                    messageBoxCustom.ShowDialog();
                                }
                            });
                        }
                    }
                    else
                    {
                        ReceiveCommand(receivedData);
                        SELF.Model.Leaning.SetMechineState(Leaning.StateMechine.Close);
                    }
                    //& " From Server"
                    StreamWriter sw = new StreamWriter(ns);
                    sw.WriteLine("###OK###");
                    sw.Flush();
                    sr.Close();
                    sw.Close();
                    ns.Close();
                    tcpCli.Close();
                }
                tcpList.Stop();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                //error
                LISTENING = false;
            }
        }

        private void ReceiveCommand(string command)
        {
            Thread thCommand = new Thread(new ParameterizedThreadStart(RunCommand));
            thCommand.Start(command);
        }

        private void RunCommand(object comm)
        {
            string receivedData = (string)comm;
            Thread.Sleep(3000);
            if (receivedData == "###SHUTDOWN###")
            {
                shutDown(ShutDown.ForcedShutdown);
            }
            else

                if (receivedData == "###REBOOT###")
                {
                    shutDown(ShutDown.ForcedReboot);
                }
                else
                    if (receivedData == "###LOGOFF###")
                    {
                        shutDown(ShutDown.ForcedLogOff);
                    }
                    
        }

        private bool IsFormAlreadyOpen(Type FormType)
        {
            foreach (Form OpenForm in Application.OpenForms)
            {
                if (OpenForm.GetType() == FormType)
                    return true;
            }

            return false;
        }

        public void shutDown(ShutDown flag)
        {
            ManagementBaseObject outParam = null;
            ManagementClass sysOS = new ManagementClass("Win32_OperatingSystem");
            sysOS.Get();
            // enables required security privilege.
            sysOS.Scope.Options.EnablePrivileges = true;
            // get our in parameters
            ManagementBaseObject inParams = sysOS.GetMethodParameters("Win32Shutdown");
            // pass the flag of 0 = System Shutdown
            inParams["Flags"] = flag;
            inParams["Reserved"] = "0";
            foreach (ManagementObject manObj in sysOS.GetInstances())
            {
                outParam = manObj.InvokeMethod("Win32Shutdown", inParams, null);
            }
        }
        #endregion

        private void picCear_Click(object sender, EventArgs e)
        {
            if (txtMain.Text == "12")
            {
                panel3.Visible = true;
            }
            else
            {
                txtMain.Text = "";
            }

        }

        #region button
        private int maxLen = 17; // maximun len of textbox include char(31),text len = maxlen - 1 
        private void lbl1_Click(object sender, EventArgs e)
        {
            if (txtMain.Text.Length < maxLen)
                SetPwd(timer1, txtMain, "1");
        }

        private void lbl2_Click(object sender, EventArgs e)
        {
            if (txtMain.Text.Length < maxLen)
                SetPwd(timer1, txtMain, "2");
        }

        private void lbl3_Click(object sender, EventArgs e)
        {
            if (txtMain.Text.Length < maxLen)
                SetPwd(timer1, txtMain, "3");
        }

        private void lbl4_Click(object sender, EventArgs e)
        {
            if (txtMain.Text.Length < maxLen)
                SetPwd(timer1, txtMain, "4");
        }

        private void lbl5_Click(object sender, EventArgs e)
        {
            if (txtMain.Text.Length < maxLen)
                SetPwd(timer1, txtMain, "5");
        }

        private void lbl6_Click(object sender, EventArgs e)
        {
            if (txtMain.Text.Length < maxLen)
                SetPwd(timer1, txtMain, "6");
        }

        private void lbl7_Click(object sender, EventArgs e)
        {
            if (txtMain.Text.Length < maxLen)
                SetPwd(timer1, txtMain, "7");
        }

        private void lbl8_Click(object sender, EventArgs e)
        {
            if (txtMain.Text.Length < maxLen)
                SetPwd(timer1, txtMain, "8");
        }

        private void lbl9_Click(object sender, EventArgs e)
        {
            if (txtMain.Text.Length < maxLen)
                SetPwd(timer1, txtMain, "9");
        }

        private void lbl0_Click(object sender, EventArgs e)
        {
            if (txtMain.Text.Length < maxLen)
                SetPwd(timer1, txtMain, "0");
        }

        private void lblLop_Click(object sender, EventArgs e)
        {
            if ((txtMain.Text.Length > 0)&&(pass.Length>0))
            {
                display = display.Substring(0, display.Length - 1);
                pass = pass.Substring(0, pass.Length - 1);
                DeleteTicker(txtMain);
            }
        }
        #endregion

        string pass = "";
        string display = "";

        private void SetPwd(System.Windows.Forms.Timer timer, RichTextBox txbRich, string pwd)
        {
            if (timer.Enabled)
            {
                timer.Stop();
            }
            else
            {
                timer.Start();
            }

            pass += pwd;
            txbRich.AppendText(pwd);
            display += "*";
            //txbRich.Text += pwd;
            if (!timer.Enabled)
            {
                timer.Start();
            }
        }

        private string SpacialChar(int code)
        {
            System.Text.Encoding Encoder = System.Text.ASCIIEncoding.Default;
            Byte[] buffer = new byte[] { (byte)code };
            string spChar = Encoding.GetEncoding(1252).GetString(buffer);
            return spChar;
        }

        private void  ChangeTicker(RichTextBox textBox)
        {
            textBox.Clear();
            textBox.Text = display + SpacialChar(31);
            textBox.SelectionStart = 0;
            textBox.SelectionAlignment = HorizontalAlignment.Right;
            textBox.SelectionLength = textBox.Text.Length - 1;
            textBox.SelectionFont = new System.Drawing.Font("symbol", 44F, System.Drawing.FontStyle.Bold);
            textBox.SelectionColor = Color.Black;
            textBox.SelectionLength = 0;
        }

        private void DeleteTicker(RichTextBox textBox)
        {
            textBox.Clear();
            HideCaret(txtMain.Handle);
            textBox.Text = display + SpacialChar(31);
            textBox.SelectionStart = 0;
            textBox.SelectionLength = textBox.Text.Length - 1;
            textBox.SelectionAlignment = HorizontalAlignment.Right;
            textBox.SelectionFont = new System.Drawing.Font("symbol", 44F, System.Drawing.FontStyle.Bold);
            textBox.SelectionColor = Color.Black;
            textBox.SelectionLength = 0;
        }

        string lateTime="";
        string postLogin = "";

        private void lblIN_Click(object sender, EventArgs e)
        {

            bool bypassLogin = false;
            if (bypassLogin)
            {
                frm_Course frmTest = new frm_Course(); //*********************************************************************
                frmTest.ShowDialog();
                txtMain.Text = "";
            }
            try
            {
                string sql = "SELECT * FROM [dbo].[DataSetting] WHERE DataSettingName ='LATE_TIME'";
                DataSet dss = conn.Retreive(sql);
                lateTime = dss.Tables[0].Rows[0]["Value"].ToString();
            }
            catch (Exception ex)
            {
                lateTime = "15";
                //throw new Exception("get late time error");
            }

            try
            {
                string sql0 = "SELECT * FROM [dbo].[DataSetting] WHERE DataSettingName ='MINS_LOGON_BEFORE'";
                DataSet dss0 = conn.Retreive(sql0);
                postLogin = dss0.Tables[0].Rows[0]["Value"].ToString();
            }
            catch (Exception ex)
            {
                postLogin = "30";
                //throw new Exception("get min login error.");
            }

            //
            //1207000000025592
            if (!bypassLogin)//if false bypass all code under this scope
            {
                string sqlCheckUseing = @"SELECT StateTicket FROM Fact_LearningTicket WHERE TicketID = '@tickrt'";
                sqlCheckUseing = sqlCheckUseing.Replace("@tickrt", pass);
                DataSet ds11 = conn.Retreive(sqlCheckUseing);
                if (ds11 != null && (ds11.Tables[0].Rows.Count > 0))
                {
                    if (ds11.Tables[0].Rows[0]["StateTicket"].ToString() == "Using")
                    {
                        Dialog_Dup dup__ticket = new Dialog_Dup();
                        dup__ticket.ShowDialog();
                    }
                    else
                    {
                        #region LOGIN
                        string sqlLogin = @"EXECUTE [dbo].[MemberLogin] @L0gTime,@Ticket,@minLate,@LoginBefor,@BranchID";
                        sqlLogin = sqlLogin.Replace("@L0gTime", "" + SELF.Model.Leaning.TimeToValue(SELF.Model.Leaning.GetServerTime()));
                        //sqlLogin = sqlLogin.Replace("@L0gTime", "1380");
                        sqlLogin = sqlLogin.Replace("@Ticket", pass);
                        sqlLogin = sqlLogin.Replace("@minLate", lateTime);
                        sqlLogin = sqlLogin.Replace("@LoginBefor", postLogin);
                        sqlLogin = sqlLogin.Replace("@BranchID", Config.Configurations.BranchID);
                        DataSet ds = conn.Retreive(sqlLogin);
                        if (ds != null && (ds.Tables[0].Rows.Count > 0))
                        {
                            Common.Member.TicketID = pass;
                            Common.Member.MemberName = ds.Tables[0].Rows[0][1].ToString();
                            //ตัดเวลาจอง
                            CalcBookTime(Common.Member.TicketID);
                            //
                            //Set Admisssion time for booking
                            //
                            SetAdmission4Booking(Common.Member.TicketID);
                            UpdateBookingState();

                            using (frm_Course frm = new frm_Course())
                            {
                                //***************************************************************************************
                                //Assign value to ticket ID
                                ticketID = ds.Tables[0].Rows[0][0].ToString();
                                frm.TicketID = Common.Member.TicketID;
                                frm.StudentName = ds.Tables[0].Rows[0][1].ToString();
                                frm.IpAddr = SELF.Model.Leaning.GetIP();
                                frm.ShowDialog();
                            }
                            display = "";
                            txtMain.Text = "";
                            pass = "";
                        }
                        else
                        {
                            Dialog_Error frm_Error = new Dialog_Error(); //**************************************************************************************************
                            frm_Error.ShowDialog();
                            //pass = "";
                        }
                        #endregion Login
                    }

                    //if end of reserv, exit code here.
                    //
                    //Thread thGetExit = new Thread(new ThreadStart(GetExit));
                    //thGetExit.Start();
                    //
                    //
                }
                else
                {
                    Dialog_Error frm_Error = new Dialog_Error(); //**************************************************************************************************
                    frm_Error.ShowDialog();
                }
            }
        }

        private void GetExit()
        {
            if (SELF.cGobal.EndOfReserv == true)
            {
                //do nothing
            }
        }
        /// <summary>
        /// EN : Calculate and update balance time in ticket
        /// TH : ตัดเวลาเรียนของ Ticket เมื่อ
        /// </summary>
        private void CalcBookTime(string TicketID)
        {
            try
            {
                //query balance time
                string sqlBalance = @"SELECT BalanceTime FROM [dbo].Fact_LearningTicket WHERE TicketID=@Ticket";
                sqlBalance = sqlBalance.Replace("@Ticket", TicketID);
                DataSet ds = conn.Retreive(sqlBalance);
                int balance = SELF.Model.Leaning.strTime2Int(ds.Tables[0].Rows[0][0].ToString());


                int time = Leaning.TimeToValue(SELF.Model.Leaning.GetServerTime());
                //query round
                string thisRound = @"EXECUTE [dbo].[FindRoundLearnning] '@TicketID',@ThisTimevalue";
                thisRound = thisRound.Replace("@TicketID", TicketID);
                thisRound = thisRound.Replace("@ThisTimevalue", time.ToString());
                DataSet ds2 = conn.Retreive(thisRound);
                if (ds2 != null && (ds2.Tables[0].Rows.Count>0))
                {
                    string aRound = ds2.Tables[0].Rows[0][0].ToString();
                    VDOStatus.RoundLogin = aRound;

                    //query book time
                    string sqlBook = @"SELECT 30*(MAX(TimeId)-MIN(TimeId)+1) FROM [dbo].Booking
                    WHERE TicketID = @ticket
                    AND [Round]= @around
                    AND [Day] = DAY(GETDATE())
                    AND [Month]=MONTH(GETDATE())
                    AND [Year]= YEAR(GETDATE())
                    AND [Admission_Time] IS NULL";
                    sqlBook = sqlBook.Replace("@ticket", TicketID);
                    sqlBook = sqlBook.Replace("@around", aRound);
                    using (DataSet ds1 = conn.Retreive(sqlBook))
                    {
                        int book = 0;
                        //check value of book time, if user already logon set book=0, if not calc it. 
                        try
                        {
                            book = Convert.ToInt32(ds1.Tables[0].Rows[0][0]);
                        }
                        catch(Exception ex)
                        {
                            book = 0;
                            Console.WriteLine(ex.Message);
                        }
                        int remain = balance - book;
                        string strRemain = SELF.Model.Leaning.Int2Time(remain);
                        string sqlUpdBalance = @"UPDATE [dbo].[Fact_LearningTicket]
                                                SET [dbo].[Fact_LearningTicket].BalanceTime = '@BalaceTime'
                                                WHERE [dbo].[Fact_LearningTicket].TicketID = '@Ticket'";
                        sqlUpdBalance = sqlUpdBalance.Replace("@BalaceTime", strRemain);
                        sqlUpdBalance = sqlUpdBalance.Replace("@Ticket", TicketID);
                        conn.Execute(sqlUpdBalance);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Application Error. Please contact system administrator.");
            }

        }

        private void UpdateBookingState()
        {
            try
            {
                int time = Leaning.TimeToValue(SELF.Model.Leaning.GetServerTime());
                string setBookSQL = @"UPDATE [dbo].[Booking]
                SET [BookState] = '1' 
                WHERE [Round] = @Round";
                setBookSQL = setBookSQL.Replace("@Round", VDOStatus.RoundLogin);

                conn.Execute(setBookSQL);
            }
            catch (Exception ex) 
            {
                //throw new Exception("Error while update booking state");
            }

        }

        private void SetAdmission4Booking(string SetAdmission4Booking_TicketID)
        {
            try
            {
                int time = Leaning.TimeToValue(SELF.Model.Leaning.GetServerTime());
                string setBookSQL = @"UPDATE [dbo].[Booking]
                SET Admission_Time = PARSENAME(REPLACE(convert(varchar(50),getdate(),108), ':', '.'), 3) +':'+PARSENAME(REPLACE(convert(varchar(50),getdate(),108), ':', '.'), 2) +' น.'
                WHERE TicketID = @TicketID
                AND [dbo].[Booking].[Month]=MONTH(GETDATE())
                AND [dbo].[Booking].[Day] = DAY(GETDATE())
                AND [dbo].[Booking].[Year] = YEAR(GETDATE())
                AND [Round] = @Round";
                setBookSQL = setBookSQL.Replace("@TicketID", SetAdmission4Booking_TicketID);
                setBookSQL = setBookSQL.Replace("@ThisTimevalue", time.ToString());
                setBookSQL = setBookSQL.Replace("@Round", VDOStatus.RoundLogin);

                conn.Execute(setBookSQL);
            }
            catch (Exception ex)
            {
                //
                //throw new Exception("Error in SetAdmission4Booking.");
            }
        }

        private void lblNew_Click(object sender, EventArgs e)
        {
            string sql = @"SELECT [Value]
              FROM [dbo].[DataSetting]
              WHERE [DataSettingName] = 'EXIT_CODE'";
            DataSet dss = conn.Retreive(sql);
            if (dss != null)
            {
                string exit_code = dss.Tables[0].Rows[0][0].ToString();
                if (pass == exit_code)
                {
                    if (Check)
                    {
                        Check = false;
                        panel3.Visible = true;
                    }
                    else
                    {
                        Check = true;
                        panel3.Visible = false;
                    }
                }
                else
                {
                    txtMain.Text = "";
                    display = "";
                    pass = "";
                }
            }
            else
            {
                txtMain.Text = "";
                display = "";
                pass = "";
            }
        }

        private void frm_Main_New_Paint(object sender, PaintEventArgs e)
        {
            SELF.Model.Leaning.SetMechineState(Leaning.StateMechine.Open);
        }

        private void frm_Main_New_FormClosing(object sender, FormClosingEventArgs e)
        {
            BatchUnmapDrive();
        }


    }
}